package mrt.cse.gajanidu.Manager;


import org.apache.zookeeper.data.Stat;

import java.util.List;

public class Manager extends NodeWatcher implements Runnable {
    public static int count = 0;

    public Manager(String name) {
        this.managerName = name;
    }

    public void invoke() {

        Stat stat = isNodeExist(defPath, false);
        if (stat != null) {
            createZnode(defPath + "/" + managerName, managerName);
            System.out.println("INFO :  " + managerName + " joined to the Manager Cloud");
            List<String> childList = getChildrenOfMainNode();
            //If there are no children assign him self as the Coordinator
            if (childList.size() == 1) {
                assignCoordinatorMySelf(childList.get(0), getZidOfNode(childList.get(0)));
            } else {
                processForCoordinator();
            }
            addWatcher();
        } else {
            System.out.println("ERROR : Cannot find the Root Znode.");
        }

    }

    @Override
    public void run() {
        connectToServer("localhost");
        invoke();
        try {
            synchronized (this) {
                while (!expired) {
                    wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
